package com.youlai.boot.form.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.form.mapper.FormCollectRecordMapper;
import com.youlai.boot.form.model.entity.*;
import com.youlai.boot.form.model.form.FormCollectRecordForm;
import com.youlai.boot.form.service.*;
import com.youlai.boot.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class FormCollectRecordServiceImpl extends ServiceImpl<FormCollectRecordMapper, FormCollectRecord> implements FormCollectRecordService {

    private final FormDefinitionService formDefinitionService;
    private final FormDataService formDataService;
    private final FormCollectTaskService formCollectTaskService;
    private final FormCollectTargetService formCollectTargetService;
    private final FormDataFieldService formDataFieldService;

    /**
     * 填写表单
     *
     * @param collectRecordForm
     * @return
     */
    @Override
    public Long fillTask(FormCollectRecordForm collectRecordForm) {
        FormCollectTask formCollectTask = formCollectTaskService.getById(collectRecordForm.getTaskId());
        // todo 通过用户id查询用户姓名
        FormCollectRecord collectRecord = FormCollectRecord.builder()
                .taskId(collectRecordForm.getTaskId())
                .formId(formCollectTask.getFormId())
                .targetId(collectRecordForm.getTargetId())
                .submitTime(LocalDateTime.now())
                .formData(JSONObject.toJSONString(collectRecordForm.getFormData()))
                .status(0)
                .build();
        FormDefinition formDefinition = formDefinitionService.getById(collectRecord.getFormId());
        collectRecord.setVersion(formDefinition.getVersion());
        // 保存并返回ID
        boolean result = this.saveOrUpdate(collectRecord);
        if (result) {
            return collectRecord.getId(); // 返回新增记录的ID
        } else {
            throw new RuntimeException("填写失败");
        }
    }

    /**
     * 提交表单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Boolean submitTask(Long id) {
        FormCollectRecord formCollectRecord = this.getById(id);
        FormCollectTask formCollectTask = formCollectTaskService.getById(formCollectRecord.getTaskId());
        // 根据任务id和用户id查找唯一任务target
        FormCollectTarget formCollectTarget = formCollectTargetService.getOne(
                new LambdaQueryWrapper<FormCollectTarget>()
                        .eq(FormCollectTarget::getTaskId, formCollectTask.getId())
                        .eq(FormCollectTarget::getTargetId, formCollectRecord.getTargetId()));
        // 判断提交次数是否大于最大提交次数
        if (formCollectTarget.getSubmitCount() >= formCollectTask.getMaxSubmitCount()) {
            throw new RuntimeException("最大提交次数为" + formCollectTask.getMaxSubmitCount() + "，提交次数已超过最大提交次数");
        }
        // 更新FormCollectTarget
        formCollectTarget.setSubmitCount(formCollectTarget.getSubmitCount() + 1);
        formCollectTarget.setLastSubmitTime(LocalDateTime.now());
        formCollectTargetService.updateById(formCollectTarget);
        // 更新FormCollectRecord
        formCollectRecord.setStatus(1);
        formCollectRecord.setSubmitTime(LocalDateTime.now());
        this.updateById(formCollectRecord);

        // 构建FormData对象保存
        FormDefinition formDefinition = formDefinitionService.getById(formCollectRecord.getFormId());
        FormData formData = FormData.builder()
                .formCode(formDefinition.getFormCode())
                .dataJson(formCollectRecord.getFormData())
                .submitUser(formCollectRecord.getTargetName())
                .submitTime(formCollectRecord.getSubmitTime())
                .createBy(SecurityUtils.getUserId())
                .formCode(formDefinition.getFormCode())
                .build();
        formDataService.save(formData);

        // 构建formDataFiled对象保存
        Map<String, Object> dataMap = JSONObject.parseObject(formCollectRecord.getFormData(), Map.class);
        if (dataMap == null || dataMap.isEmpty()) {
            log.error("formCollectRecord的formData表单数据为空");
        }
        JSONObject jsonObject = JSONObject.parseObject(formDefinition.getFormSchema());
        if (jsonObject == null) {
            log.error("FormSchema反序列化失败");
        }
        JSONArray schemasArray = jsonObject.getJSONArray("schemas");
        if (schemasArray == null || schemasArray.isEmpty()) {
            log.error("FormSchema提取schemas失败.");
        }
        JSONObject pageSchema = schemasArray.getJSONObject(0);
        JSONArray childrenArray = pageSchema.getJSONArray("children");
        List<Object> childrenList = childrenArray.toJavaList(Object.class);
        List<FormDataFiled> formDataFiledList = new ArrayList<>();
        dataMap.forEach((field, value) -> {
            for (Object children : childrenList){
                JSONObject childrenJsonObject = (JSONObject) children;
                String childrenField = childrenJsonObject.getString("field");
                if (childrenField.equals(field)){
                    FormDataFiled formDataFiled = FormDataFiled.builder()
                            .formDataId(formData.getId())
                            .formCode(formDefinition.getFormCode())
                            .createBy(SecurityUtils.getUserId())
                            .build();
                    formDataFiled.setFieldLabel(childrenJsonObject.getString("label"));
                    formDataFiled.setFieldType(childrenJsonObject.getString("type"));
                    formDataFiled.setFieldKey(field);
                    try {
                        if (value instanceof String) {
                            formDataFiled.setFieldValueStr(String.valueOf(value));
                        } else if (value instanceof Number) {
                            formDataFiled.setFieldValueStr(String.valueOf(value));
                            formDataFiled.setFieldValueNum(((Integer) value).doubleValue());
                        } else if ((value instanceof java.time.LocalDateTime ||
                                value instanceof java.time.LocalDate ||
                                value instanceof java.time.LocalTime ||
                                value instanceof java.util.Date)) {
                            formDataFiled.setFieldValueStr(String.valueOf(value));
                            formDataFiled.setFieldValueDate((LocalDateTime) value);
                        }
                    } catch (Exception e) {
                        log.error("字段值设置失败", e);
                    }
                    formDataFiledList.add(formDataFiled);
                    break;
                }
            }
        });
        return formDataFieldService.saveBatch(formDataFiledList);
    }
}
